package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@WebServlet("/CheckIP")
public class CheckIP extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = req.getServletContext();
        String realPath = context.getRealPath("IP.txt");
        System.out.println(realPath);
        Writer writer = new FileWriter(realPath);
        for (int i = 0; i < 1000; i++) {
            String ip = new Random().nextInt(255) + "." + new Random().nextInt(255) + "." + new Random().nextInt(255) + "." + new Random().nextInt(255);
            writer.write(ip + "\n");
        }
        writer.close();
        InputStream in = new FileInputStream(realPath);
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
        String str;
        Map<String, Integer> ipMap = new HashMap<>();
        while ((str = br.readLine()) != null) {
            if (ipMap.get(str) == null) {
                ipMap.put(str, 1);
            } else {
                Integer val = ipMap.get(str);
                ipMap.put(str, ++val);
            }
        }
        br.close();
        ObjectMapper mapper = new ObjectMapper();
        resp.getWriter().print(mapper.writeValueAsString(ipMap));
    }
}
